package com.ruoyi.web.Utils.validators.impl;


import com.ruoyi.web.Utils.exceptions.MobileException;
import com.ruoyi.web.Utils.validators.IsMobile;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @author wjz
 * @date 2020/12/3
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {
    private static final Pattern PATTERN = Pattern.compile("^1[345678]\\d{9}$");
    private boolean isRequired = false;

    @Override
    public void initialize(IsMobile constraint) {
        isRequired = constraint.isRequired();
    }

    @SneakyThrows
    @Override
    public boolean isValid(String obj, ConstraintValidatorContext context) {
        if (isRequired) {
            if (IsMobileValidator.isMobile(obj)) {
                return true;
            } else {
                throw new MobileException("手机号格式检验异常");
            }
        } else {
            if (StringUtils.isEmpty(obj)) {
                return true;
            } else {
                if (IsMobileValidator.isMobile(obj)) {
                    return true;
                } else {
                    throw new MobileException("手机号格式检验异常");
                }
            }
        }

    }

    private static boolean isMobile(String obj) {
        return PATTERN.matcher(obj).matches();
    }
}
